<?php

namespace app\common\model;

use app\admin\model\course\Order;
use app\admin\model\user\School;
use app\admin\model\user\TeacherCategory;
use think\Db;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    /*
   * 用户绑定openid
   * */
    public function bindOpenId($openId,$platform){
        $third = \addons\third\model\Third::where(['openid' => $openId,"user_id"=>0,'platform'=>$platform])->find();

//        dump($third);exit;
        if($third){
//            //更新头像和昵称
//            $this->nickname = $third["openname"];
//            $this->avatar = $third["avatar"];
//            $this->save();
            $third->save(["user_id"=>$this["id"]]);
        }
    }

    /*
     * 获取老师列表
     * */
    public function getTeacherList($condition){

        $condition['status'] = "normal";
        $condition['is_show'] = "1";
        if(isset($condition['works_category_id'])){
            $list = $this->where('FIND_IN_SET("' . $condition['works_category_id'] . '",works_category_id)');
            unset($condition['works_category_id']);
        }else{
            $list = $this;
        }
        $list = $list
            ->where($condition)
            ->field("id,nickname,bio,avatar")
            ->paginate();
        foreach ($list as $key => $value){
            $value['avatar'] = deal_img_url($value['avatar']);
        }
        return $list;
    }

    public function getTeacherInfo($condition){
        $condition["user_type"] = 2;
        $info = $this->where($condition)
            ->field("id,nickname,bio,avatar,works_images,honor_images,works_category_id,school_id,wechat_url")
            ->find();
        if(!$info){
            $info = [
                "id" => 0,
                "avatar" => "",
                "nickname" => "暂无",
                "works_images" => '',
                "honor_images" => '',
                "works_category_id" => '',
                "school_id" => 0,
            ];
//            exception("未找到当前老师");
        }
        return $this->dealTeacherInfo($info);
    }
    public function dealTeacherInfo($info){
        //作品
        $works_images_arr = [];
        if($info['works_images']){
            $works_images_arr = explode(",",$info['works_images']);
            foreach ($works_images_arr as $key => &$value){
                $value = deal_img_url($value);
            }
        }
        $info['works_images'] = $works_images_arr;
        $info['avatar'] = deal_img_url($info['avatar']);

        //荣誉证书
        $honor_images_arr = [];
        if($info['honor_images']){
            $honor_images_arr = explode(",",$info['honor_images']);
            foreach ($honor_images_arr as $key => &$value){
                $value = deal_img_url($value);
            }
        }
        $info['honor_images'] = $honor_images_arr;

        //分类
        $category = [];
        if($info['works_category_id']){
            $category_arr = explode(",",$info['works_category_id']);
            $category = TeacherCategory::whereIn("id",$category_arr)->column("name");
        }
        $info['category'] = $category;
        //校区
        $info['school'] = School::where("id",$info['school_id'])->value("name")??'';

        return $info;
    }


    /*
     * 获取充值最低金额
     * */
    public static function getRechargeLowMoney($user){
        $recharge_low_money = \config("site.recharge_low_money");

        if($user['is_vip'] == 0){
            //首次充值必须是15000
            $vip_money = \config("site.vip_money");
            $recharge_count = MoneyLog::where("user_id",$user['id'])
                ->where("from_type", MoneyLog::RECHARGE_MONEY)
                ->count();
            if($recharge_count == 0){
                $recharge_low_money = $vip_money;
            }

            //购买指定次数客服后 变成 5000
            $buy_course_count = \config("site.buy_course_count");
            $course_count = Order::where("user_id",$user['id'])
                ->where("status",">=",Order::STATUS_PAY)
                ->count();
            if($course_count >= $buy_course_count && $recharge_count == 0){
                $recharge_low_money = $recharge_low_money;
            }
        }
        return $recharge_low_money;
    }

    public static function getTeacherName($teacher_id){
        return self::where("id",$teacher_id)->value("nickname")??'';
    }
}
